package com.ihg.hiex.admin.handler.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.utils.StringUtils;
import com.ihg.hiex.admin.entity.upload.OnlineReport;
import com.ihg.hiex.admin.entity.upload.OnlineReportUploadItem;
import com.ihg.hiex.admin.handler.FileHandler;
import com.ihg.hiex.admin.handler.support.FileStorage;

/**
 *
 * @author Ark
 *
 */
@Component("fileHandler")
public class FileHandlerImpl implements FileHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(FileHandlerImpl.class);
    
    @Value("#{config['cloud.path']}")
    private String cloudPath;
    
    @Value("#{cloud['cloud.host']}")
    private String cloudHost;

    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.handler.FileHandler#save(com.demo2do.fms.admin.handler.FileStorage, java.io.InputStream)
     */
    public String save(FileStorage fileStorage, InputStream inputStream) {
        
        try {
            
            String parentPath = this.cloudPath + "/" +fileStorage.getPath();
            File parentFile = new File(parentPath);
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            
            // 1. 新建文件 （新建文件名为系统指定文件名，扩展名为源文件扩展名， 路径为指定路径）
            File file = new File(parentPath, fileStorage.getFileName());
            
            // 2. 将字节流copy到新文件
            FileUtils.copyInputStreamToFile(inputStream, file);
            
        } catch (IOException e) {
            logger.error("#save() - save failed, exception=[{}]", e);
            throw new BusinessException("文件存储失败");
        }
        
        // 3. 返回文件路径 + 文件名 + 扩展名
        return StringUtils.connect(cloudHost, "/", fileStorage.getPath(), "/", fileStorage.getFileName());
    }
    
    /*
     * (non-Javadoc)
     * @see com.ihg.hiex.admin.handler.FileHandler#batchSave(java.lang.String, java.util.List)
     */
    public List<OnlineReport> batchSave(String path, List<OnlineReportUploadItem> items) {
        
        List<OnlineReport> result = new ArrayList<OnlineReport>();
        
        try {
              for(OnlineReportUploadItem item : items) {
                  // generate wave report
                  String currentPath = path + "/" + item.getDelegateName() + "/report";
                  FileStorage waveFileStorage = new FileStorage(currentPath, "wave_report", FilenameUtils.getExtension(item.getWaveReport().getOriginalFilename()));
                  String waveReport = this.save(waveFileStorage, item.getWaveReport().getInputStream());
                
                  // generate wave delegate report
                  FileStorage waveDelegateFileStorage = new FileStorage(currentPath, "wave_delegate_report", FilenameUtils.getExtension(item.getWaveReport().getOriginalFilename()));
                  String waveDelegateReport = this.save(waveDelegateFileStorage, item.getWaveReport().getInputStream());
                
                  // generate swift report
                  FileStorage swiftFileStorage = new FileStorage(currentPath, "swift_report", FilenameUtils.getExtension(item.getSwiftReport().getOriginalFilename()));
                  String swiftReport = this.save(swiftFileStorage, item.getSwiftReport().getInputStream());
                  
                  OnlineReport onlineReport = new OnlineReport(item.getDelegateId(), waveReport, waveDelegateReport, swiftReport);
                  result.add(onlineReport);
              }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
}
